<template>
  <div class="forgot-password-container">
  <!-- 左侧背景 -->
  <div class="left-section">
        <transition-group name="fade">
          <img v-for="(bg, index) in backgroundImages" :key="index" :src="bg"
            :class="['bg-image', { active: currentBgIndex === index }]" alt="京剧背景">
        </transition-group>
        <div class="content-overlay"></div>
      </div>

    <!-- 右侧重置密码区域 -->
    <div class="right-section">
      <div class="right-content">
        <!-- 标题部分 -->
        <div class="title-section">
          <h1>京剧苑</h1>
          <p>传承国粹 · 弘扬文化</p>
        </div>

        <!-- 重置密码表单 -->
        <div class="reset-box">
          <h2 class="form-title">重置密码</h2>
          <el-tabs v-model="activeTab" class="reset-tabs">
            <!-- 手机号重置 -->
            <el-tab-pane label="手机号重置" name="phone">
              <el-form ref="phoneForm" :model="phoneForm" :rules="phoneRules">
                <el-form-item prop="phone">
                  <el-input
                    v-model="phoneForm.phone"
                    placeholder="请输入手机号"
                    prefix-icon="el-icon-mobile-phone"
                  ></el-input>
                </el-form-item>
                <el-form-item prop="code">
                  <div class="code-input-group">
                    <el-input
                      v-model="phoneForm.code"
                      placeholder="请输入验证码"
                      prefix-icon="el-icon-key"
                    ></el-input>
                    <el-button 
                      class="code-btn"
                      @click="sendPhoneCode"
                      :disabled="phoneCodeTimer > 0"
                    >
                      {{ phoneCodeTimer > 0 ? `${phoneCodeTimer}s` : '获取验证码' }}
                    </el-button>
                  </div>
                </el-form-item>
                <el-form-item prop="newPassword">
                  <el-input
                    v-model="phoneForm.newPassword"
                    type="password"
                    placeholder="请输入新密码"
                    prefix-icon="el-icon-lock"
                    show-password
                  ></el-input>
                </el-form-item>
                <el-form-item prop="confirmPassword">
                  <el-input
                    v-model="phoneForm.confirmPassword"
                    type="password"
                    placeholder="请确认新密码"
                    prefix-icon="el-icon-lock"
                    show-password
                  ></el-input>
                </el-form-item>
                <el-button type="primary" @click="handlePhoneReset" :loading="loading">重置密码</el-button>
              </el-form>
            </el-tab-pane>

            <!-- 邮箱重置 -->
            <el-tab-pane label="邮箱重置" name="email">
              <el-form ref="emailForm" :model="emailForm" :rules="emailRules">
                <el-form-item prop="email">
                  <el-input
                    v-model="emailForm.email"
                    placeholder="请输入邮箱"
                    prefix-icon="el-icon-message"
                  ></el-input>
                </el-form-item>
                <el-form-item prop="code">
                  <div class="code-input-group">
                    <el-input
                      v-model="emailForm.code"
                      placeholder="请输入验证码"
                      prefix-icon="el-icon-key"
                    ></el-input>
                    <el-button 
                      class="code-btn"
                      @click="sendEmailCode"
                      :disabled="emailCodeTimer > 0"
                    >
                      {{ emailCodeTimer > 0 ? `${emailCodeTimer}s` : '获取验证码' }}
                    </el-button>
                  </div>
                </el-form-item>
                <el-form-item prop="newPassword">
                  <el-input
                    v-model="emailForm.newPassword"
                    type="password"
                    placeholder="请输入新密码"
                    prefix-icon="el-icon-lock"
                    show-password
                  ></el-input>
                </el-form-item>
                <el-form-item prop="confirmPassword">
                  <el-input
                    v-model="emailForm.confirmPassword"
                    type="password"
                    placeholder="请确认新密码"
                    prefix-icon="el-icon-lock"
                    show-password
                  ></el-input>
                </el-form-item>
                <el-button type="primary" @click="handleEmailReset" :loading="loading">重置密码</el-button>
              </el-form>
            </el-tab-pane>
          </el-tabs>

          <div class="login-link">
            想起密码了？<router-link to="/login">立即登录</router-link>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import bg1 from '@/assets/opera_bg1.jpg'
import bg2 from '@/assets/opera_bg2.jpg'
import bg3 from '@/assets/opera_bg3.jpg'
import service from '@/utils/request'
import CryptoJS from 'crypto-js'

export default {
  data() {
    // 确认密码的验证规则
    const validateConfirmPassword = (rule, value, callback) => {
      const form = this[this.activeTab + 'Form'];
      if (value === '') {
        callback(new Error('请再次输入密码'));
      } else if (value !== form.newPassword) {
        callback(new Error('两次输入密码不一致'));
      } else {
        callback();
      }
    };

    return {
      activeTab: 'phone',
      loading: false,
      phoneCodeTimer: 0,
      emailCodeTimer: 0,
      backgroundImages: [bg1, bg2, bg3],
      currentBgIndex: 0,
      // 手机号表单
      phoneForm: {
        phone: '',
        code: '',
        newPassword: '',
        confirmPassword: ''
      },
      // 邮箱表单
      emailForm: {
        email: '',
        code: '',
        newPassword: '',
        confirmPassword: ''
      },
      // 手机号验证规则
      phoneRules: {
        phone: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
        ],
        code: [
          { required: true, message: '请输入验证码', trigger: 'blur' },
          { len: 6, message: '验证码长度应为6位', trigger: 'blur' }
        ],
        newPassword: [
          { required: true, message: '请输入新密码', trigger: 'blur' },
          { min: 6, message: '密码长度不能小于6位', trigger: 'blur' }
        ],
        confirmPassword: [
          { required: true, validator: validateConfirmPassword, trigger: 'blur' }
        ]
      },
      // 邮箱验证规则
      emailRules: {
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
        ],
        code: [
          { required: true, message: '请输入验证码', trigger: 'blur' },
          { len: 6, message: '验证码长度应为6位', trigger: 'blur' }
        ],
        newPassword: [
          { required: true, message: '请输入新密码', trigger: 'blur' },
          { min: 6, message: '密码长度不能小于6位', trigger: 'blur' }
        ],
        confirmPassword: [
          { required: true, validator: validateConfirmPassword, trigger: 'blur' }
        ]
      }
    }
  },
  mounted() {
    // 设置页面标题
    document.title = '京剧苑 - 重置密码';
    // 启动背景图轮播
    this.startBackgroundRotation();
  },
  beforeDestroy() {
    // 组件销毁前清除定时器
    if (this.bgRotationTimer) {
      clearInterval(this.bgRotationTimer);
    }
  },
  methods: {
    // 开始背景图轮播
    startBackgroundRotation() {
      this.bgRotationTimer = setInterval(() => {
        this.currentBgIndex = (this.currentBgIndex + 1) % this.backgroundImages.length;
      }, 5000);
    },

    // 发送手机验证码
    sendPhoneCode() {
      this.$refs.phoneForm.validateField('phone', valid => {
        if (!valid) {
          service.get('/api/system/verification/send-phone-code', {
            phone: this.phoneForm.phone
          })
            .then(res => {
              if (res.code === 200) {
                this.$message.success('验证码已发送')
                this.phoneCodeTimer = 60
                const timer = setInterval(() => {
                  this.phoneCodeTimer--
                  if (this.phoneCodeTimer <= 0) {
                    clearInterval(timer)
                  }
                }, 1000)
              } 
            })
            .catch(err => {
              this.$message.error('发送失败，请稍后重试')
              console.error(err)
            })
        }
      })
    },

    // 发送邮箱验证码
    sendEmailCode() {
      this.$refs.emailForm.validateField('email', valid => {
        if (!valid) {
          service.get('/api/system/verification/send-email-code', {
            email: this.emailForm.email
          })
            .then(res => {
              if (res.code === 200) {
                this.$message.success('验证码已发送')
                this.emailCodeTimer = 60
                const timer = setInterval(() => {
                  this.emailCodeTimer--
                  if (this.emailCodeTimer <= 0) {
                    clearInterval(timer)
                  }
                }, 1000)
              } 
            })
            .catch(err => {
              this.$message.error('发送失败，请稍后重试')
              console.error(err)
            })
        }
      })
    },

    // 手机号重置密码
    handlePhoneReset() {
      this.$refs.phoneForm.validate(valid => {
        if (valid) {
          this.loading = true;
          // 对新密码进行加密
          const encryptedPassword = CryptoJS.MD5(this.phoneForm.newPassword).toString()
          const dataToSend = { ...this.phoneForm, newPWD: encryptedPassword }; // 用加密后的密码替换原密码
          
          service.put('/api/system/user/resetpwdByphone', dataToSend)
            .then(res => {
              if (res.code === 200) {
                this.$message.success('密码重置成功');
                this.$router.push('/login');
              } 
            })
            .catch(err => {
              this.$message.error('重置失败，请稍后重试');
              console.error(err);
            })
            .finally(() => {
              this.loading = false;
            });
        }
      });
    },

    // 邮箱重置密码
    handleEmailReset() {
      this.$refs.emailForm.validate(valid => {
        if (valid) {
          this.loading = true;
          // 对新密码进行加密
          const encryptedPassword = CryptoJS.MD5(this.emailForm.newPassword).toString();
          const dataToSend = { ...this.emailForm, newPWD: encryptedPassword }; // 用加密后的密码替换原密码
          
          service.put('/api/system/user/resetpwdByemail', dataToSend)
            .then(res => {
              if (res.code === 200) {
                this.$message.success('密码重置成功');
                this.$router.push('/login');
              } 
            })
            .catch(err => {
              this.$message.error('重置失败，请稍后重试');
              console.error(err);
            })
            .finally(() => {
              this.loading = false;
            });
        }
      });
    }
  }
}
</script>

<style scoped>
/* 全局样式 */
html, body {
  margin: 0;
  padding: 0;
  height: 100%;
  width: 100%;
}

#app {
  height: 100%;
  width: 100%;
}

/* 容器样式 */
.forgot-password-container {
  display: flex;
  min-height: 100vh;
  width: 100vw;
  overflow: hidden;
}

/* 左侧样式 */
.left-section {
  flex: 1.2;
  position: relative;
  overflow: hidden;
}

.bg-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
  position: absolute;
  top: 0;
  left: 0;
  opacity: 0;
  transition: opacity 1s ease-in-out;
}

.bg-image.active {
  opacity: 1;
}

/* 过渡动画 */
.fade-enter-active, .fade-leave-active {
  transition: opacity 1s;
}

.fade-enter, .fade-leave-to {
  opacity: 0;
}

.content-overlay {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: linear-gradient(135deg, rgba(139, 0, 0, 0.6), rgba(0, 0, 0, 0.6));
}

/* 右侧样式 */
.right-section {
  width: 550px;
  background: linear-gradient(135deg, #8B0000 0%, #4A0404 100%);
  padding: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.right-content {
  width: 100%;
  max-width: 400px;
}

/* 标题样式 */
.title-section {
  text-align: center;
  margin-bottom: 40px;
  position: relative;
}

.title-section h1 {
  font-family: 'STXingkai', 'STZhongsong', serif;
  font-size: 48px;
  color: #FFD700;
  margin: 0;
  text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.5);
  letter-spacing: 8px;
  padding-bottom: 15px;
  position: relative;
}

.title-section h1::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 50%;
  transform: translateX(-50%);
  width: 180px;
  height: 2px;
  background: linear-gradient(90deg, 
    transparent,
    rgba(255, 215, 0, 0.3),
    #FFD700,
    rgba(255, 215, 0, 0.3),
    transparent
  );
}

.title-section p {
  font-size: 18px;
  color: #FFD700;
  margin-top: 15px;
  font-family: 'STZhongsong', sans-serif;
  letter-spacing: 4px;
}

/* 重置密码框样式 */
.reset-box {
  background: rgba(0, 0, 0, 0.2);
  padding: 30px;
  border-radius: 10px;
  border: 1px solid rgba(255, 215, 0, 0.3);
}

/* 表单主标题 */
.form-title {
  text-align: center;
  color: #FFD700;
  font-size: 24px;
  margin: 0 0 20px;
  font-family: 'STZhongsong', sans-serif;
  letter-spacing: 2px;
}

/* 标签页样式 */
.reset-tabs >>> .el-tabs__nav {
  width: 100%;
  display: flex;
}

.reset-tabs >>> .el-tabs__item {
  flex: 1;
  text-align: center;
  color: #FFD700;
  font-size: 16px;
  padding: 0 0 12px;
  font-family: 'STZhongsong', sans-serif;
}

.reset-tabs >>> .el-tabs__item.is-active {
  color: #FFD700;
  font-weight: bold;
}

.reset-tabs >>> .el-tabs__active-bar {
  background-color: #FFD700;
  height: 2px;
}

.reset-tabs >>> .el-tabs__nav-wrap::after {
  background-color: rgba(255, 215, 0, 0.2);
}

.reset-tabs >>> .el-tabs__header {
  margin-bottom: 30px;
}

/* 输入框样式 */
.el-input >>> .el-input__inner {
  height: 45px;
  background: rgba(0, 0, 0, 0.2);
  border: 1px solid rgba(255, 215, 0, 0.3);
  color: #fff;
  border-radius: 6px;
  padding-left: 45px;
  font-size: 15px;
}

.el-input >>> .el-input__inner:focus {
  border-color: #FFD700;
}

.el-input >>> .el-input__prefix {
  color: #FFD700;
  font-size: 18px;
  left: 15px;
}

/* 验证码按钮样式 */
.code-input-group {
  display: flex;
  gap: 10px;
}

.code-input-group .el-input {
  flex: 1;
}

.code-btn {
  width: 100px !important;
  height: 45px !important;
  background: linear-gradient(135deg, #8B0000 0%, #4A0404 100%) !important;
  border: 1px solid #FFD700 !important;
  color: #FFD700 !important;
  font-size: 14px !important;
  padding: 0 15px !important;
  border-radius: 6px !important;
  transition: all 0.3s !important;
}

.code-btn:hover:not([disabled]) {
  opacity: 0.9;
  border-color: #fff !important;
  color: #fff !important;
}

.code-btn[disabled] {
  background: rgba(139, 0, 0, 0.5) !important;
  border-color: rgba(255, 215, 0, 0.3) !important;
  color: rgba(255, 215, 0, 0.5) !important;
  cursor: not-allowed;
}

/* 登录链接样式 */
.login-link {
  text-align: center;
  margin-top: 20px;
  color: #FFD700;
}

.login-link a {
  color: #FFD700;
  text-decoration: none;
  margin-left: 5px;
  font-weight: bold;
}

.login-link a:hover {
  text-decoration: underline;
}

/* 按钮样式 */
.el-button--primary {
  width: 100%;
  height: 45px;
  background: linear-gradient(135deg, #8B0000 0%, #4A0404 100%);
  border: 1px solid #FFD700;
  color: #FFD700;
  font-size: 16px;
  letter-spacing: 2px;
  margin-top: 10px;
  transition: all 0.3s;
}

.el-button--primary:hover {
  opacity: 0.9;
  border-color: #fff;
  color: #fff;
}

.el-button--primary:focus, .el-button--primary:active {
  background: linear-gradient(135deg, #4A0404 0%, #8B0000 100%);
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .right-section {
    width: 500px;
  }
  
  .title-section h1 {
    font-size: 42px;
  }
}

@media (max-width: 992px) {
  .left-section {
    display: none;
  }
  
  .right-section {
    width: 100%;
  }
}

@media (max-width: 576px) {
  .right-section {
    padding: 20px;
  }
  
  .reset-box {
    padding: 20px;
  }
  
  .title-section h1 {
    font-size: 36px;
  }
}
</style> 